package com.github.pig.daemon.job.service;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.github.pig.daemon.job.constant.enums.EnumJobTaskStatus;
import com.github.pig.daemon.job.entity.JobTask;
import com.github.pig.daemon.job.handler.ElasticJobHandler;
import com.github.pig.daemon.job.mapper.JobTaskMapper;
import com.github.pig.daemon.job.util.CronUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class ActiveJobService implements JobService {

    @Autowired
    private ElasticJobHandler jobHandler;

    @Autowired
    private JobTaskMapper jobTaskMapper;

    @Override
    public void toScanAdd() {
        JobTask condition = new JobTask();
        condition.setStatus(EnumJobTaskStatus.NON_EXECUTION.getCode());
        List<JobTask> jobTaskList = jobTaskMapper.selectList(new EntityWrapper<>(condition));
        jobTaskList.forEach(jobTask -> {
            Long current = System.currentTimeMillis();
            String jobName = "job" + jobTask.getSendTime();
            String cron;
            //说明消费未发送，但是已经过了消息的发送时间，调整时间继续执行任务
            if (jobTask.getSendTime() < current) {
                //设置为一分钟之后执行，把Date转换为cron表达式
                cron = CronUtil.getCron(new Date(current + 60000));
            } else {
                cron = CronUtil.getCron(new Date(jobTask.getSendTime()));
            }
            jobHandler.addJob(jobName, cron, 1, String.valueOf(jobTask.getId()));
        });
    }
}
